package com.qx.chat.system.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.qx.chat.system.dao.AbstractRepository;
import com.qx.chat.system.entity.ChatMessageRecord;
import com.qx.chat.system.entity.Group;
import com.qx.chat.system.entity.User;
import com.qx.chat.system.message.TextMessage;

/**
 * TODO
 * @author cyf
 * @version TODO
 */
@Component
public class ChatRecordServiceImpl implements ChatRecordService{
	@Autowired
	private AbstractRepository<ChatMessageRecord> chatRecordDaoImpl;
	@Autowired
	private AbstractRepository<User> userDaoImpl;
	@Autowired
	private AbstractRepository<Group> groupDaoImpl;

	@Override
	public ChatMessageRecord insertChatMessageRecord(TextMessage message,Integer chatType) {
		// TODO Auto-generated method stub
		ChatMessageRecord record = new ChatMessageRecord();
		User speaker = userDaoImpl.findOne("loginName", message.getFrom());
		record.setSpeakerUserId(speaker.getId());
		record.setSpeakerUser(speaker);
		if(chatType == ChatMessageRecord.USERMSGRECORD){
			User audienceUser = userDaoImpl.findOne("loginName", message.getTo());
			record.setAudienceUser(audienceUser);
			record.setAudienceUserId(audienceUser.getId());
		} else if(chatType == ChatMessageRecord.GROUPMSGRECORD){
			Group group = groupDaoImpl.findById(message.getGroupId());
			User audienceUser = userDaoImpl.findOne("loginName", message.getTo());
			record.setAudienceUser(audienceUser);
			record.setAudienceUserId(audienceUser.getId());
			record.setAudienceGroup(group);
			record.setAudienceGroupId(group.getId());
		}
		record.setChatType(chatType);
		record.setContentRtf(message.getMsg());
		record.setOccureTime(message.getTime());
		chatRecordDaoImpl.insert(record);
		return record;
	}

	@Override
	public JSONArray getChatRecordPage(Date startTime, Date endTime, String myID, String friendID, int pageSize,
			int pageIndex) {
		// TODO Auto-generated method stub
		return null;
	}
}
